package cn.yuan.order.service.impl;

import cn.yuan.basic.service.impl.BaseServiceImpl;
import cn.yuan.basic.util.CodeGenerateUtils;
import cn.yuan.basic.util.PageList;
import cn.yuan.order.domain.AdoptOrder;
import cn.yuan.order.domain.OrderAddress;
import cn.yuan.order.mapper.AdoptOrderMapper;
import cn.yuan.order.mapper.OrderAddressMapper;
import cn.yuan.order.query.AdoptOrderQuery;
import cn.yuan.order.service.IAdoptOrderService;
import cn.yuan.org.domain.Employee;
import cn.yuan.org.mapper.EmployeeMapper;
import cn.yuan.pay.constants.OrderConstants;
import cn.yuan.pay.domain.PayBill;
import cn.yuan.pay.mapper.PayBillMapper;
import cn.yuan.pay.service.IPayBillService;
import cn.yuan.pet.domain.Pet;
import cn.yuan.pet.mapper.PetMapper;
import cn.yuan.quartz.constants.QuartzConstants;
import cn.yuan.quartz.service.IQuartzService;
import cn.yuan.quartz.utils.QuartzJobInfo;
import cn.yuan.user.domain.Logininfo;
import cn.yuan.user.domain.User;
import cn.yuan.user.domain.UserAddress;
import cn.yuan.user.mapper.UserAddressMapper;
import cn.yuan.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;

    @Override
    public String submit(Map<String, Object> params, Logininfo loginInfo) {
        //前台传入数据转换类型
//        service_method:'0',
//                address_id: '1',
//                pay_method:'2',
//                pet_id:null,
        System.out.println("===="+params);
        Long petId = Long.valueOf(params.get("pet_id").toString());
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        // 1.修改宠物状态下架 下架时间
        Pet pet = petMapper.loadById(petId);
        // 2.绑定领养人
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        if(pet!=null){
            pet.setState(0);
            pet.setOffsaletime(new Date());
            pet.setUser_id(user.getId());
            petMapper.update(pet);
        }
        //3.生成订单  快速抽取方法  alt + shift + m
        AdoptOrder order = initAdoptOrder(petId, pet, user);
        String unionPaySn = CodeGenerateUtils.generateUnionPaySn();
        order.setPaySn(unionPaySn);
        adoptOrderMapper.save(order);

        //4.订单地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);
        //5. @TODO 支付
        //5.1创建支付单并发起支付请求
        //5.1.1 创建支付单
        PayBill payBill = initPayBill(payMethod, pet, user, order);
        payBillMapper.save(payBill);
        //5.1.2 对支付单发起支付请求-就是支付模块给我提供一个支付接口service方法
        String payData = payBillService.pay(payBill);
        //6. @TODO 订单定时取消
        QuartzJobInfo info = new QuartzJobInfo();
        info.setType(QuartzConstants.ORDER_ADOPT_TYPE_CANCEL);
        String jobName = QuartzConstants.ORDER_ADOPT_CANCEL_PREFIX + order.getPaySn();
        info.setJobName(jobName);
        Map<String, Object> paramsQuartz = new HashMap<>();
        paramsQuartz.put("orderId", order.getId());
        info.setParams(paramsQuartz);
        info.setFireDate(order.getLastPayTime());
        //添加超时未支付取消定时任务
        quartzService.addJob(info);
        System.out.println(order.getDigest()+"添加定时任务成功");
        return payBillService.pay(payBill);
    }

    private PayBill initPayBill(Long payMethod, Pet pet, User user, AdoptOrder order) {
        PayBill payBill = new PayBill();
        payBill.setDigest(order.getDigest());
        payBill.setMoney(order.getPrice());
        payBill.setUnionPaySn(order.getPaySn());
        payBill.setState(0);
        payBill.setLastPayTime(new Date(System.currentTimeMillis()+ OrderConstants.ORDER_TIMEOUT));
        payBill.setPayChannel(Long.valueOf(payMethod));
        payBill.setBusinessType(OrderConstants.BUSINESS_TYPE_ADOPT_ORDER);
        payBill.setBusinessKey(order.getId());
        payBill.setUser_id(user.getId());
        payBill.setShop_id(pet.getShop_id());
        payBill.setNickName(user.getUsername());
        return payBill;
    }

    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, Long loginInfoId) {
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfoId);
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryForPage(query);
    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, Long loginInfoId) {
        User user = userMapper.loadByLoginInfoId(loginInfoId);
        if(user!=null){
            query.setUserId(user.getId());
        }
        return super.queryForPage(query);
    }

    @Override
    public AdoptOrder findOne(Long businessKey) {
        return adoptOrderMapper.findOne(businessKey);
    }


    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        //拷贝的时候直接将id也拷贝过来了，所以要指空
        orderAddress.setId(null);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Long petId, Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        //设置订单内容
        order.setDigest("[摘要]"+pet.getName()+"的领养订单");
        order.setPrice(pet.getSaleprice());
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        order.setLastPayTime(new Date(System.currentTimeMillis()+15*60*1000));
        order.setPet_id(petId);
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        return order;
    }

    @Override
    public void quartzCancel(Long orderId) {
        //修改领养订单状态
        AdoptOrder order = adoptOrderMapper.loadById(orderId);
        order.setState(-1);
        adoptOrderMapper.update(order);
        //修改支付单状态
        String unionPaySn = order.getPaySn();
        PayBill bill = payBillMapper.loadByUnionPaySn(unionPaySn);
        bill.setState(-1);
        payBillMapper.update(bill);
        System.out.println(order.getDigest()+":订单被Quartz取消了！");
    }
}
